package se.perp.c4.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class HelpWindow extends JFrame implements ActionListener, HyperlinkListener {

    private JPanel panel = new JPanel(new BorderLayout());
    private JButton okButton = new JButton("OK");
    private JTextPane textPane = new JTextPane();
    private JScrollPane scrollPane = new JScrollPane();
    private final String LOAD_ERROR_MSG = "Unable to display help text.\nCan't find help file: ";

    public HelpWindow(String title, String helpFile) {
        super("Confrontation help");

        setIconImage(Images.get(Images.Which.APPICON));

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        setPreferredSize(new Dimension(300, 600));

        textPane.setEditable(false);
        textPane.addHyperlinkListener(this);
        URL url = getClass().getResource(helpFile);
        try {
            textPane.setPage(url);
        } catch (IOException ex) {
            showLoadErrorMsgBox(url);
        }

        scrollPane.getViewport().add(textPane);
        panel.add(scrollPane, BorderLayout.CENTER);

        okButton.setMnemonic('O');
        okButton.setToolTipText("Closes this window.");
        okButton.addActionListener(this);

        JPanel southPanel = new JPanel();
        southPanel.add(okButton);

        panel.add(southPanel, BorderLayout.SOUTH);

        add(panel);

        pack();
        setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {
        dispose();
    }

    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            try {
                textPane.setPage(e.getURL());
            } catch (IOException ioe) {
                showLoadErrorMsgBox(e.getURL());
            }
        }
    }

    private void showLoadErrorMsgBox(URL url) {
        JOptionPane.showMessageDialog(null, LOAD_ERROR_MSG + url.getFile(),
                "Could not load help", JOptionPane.ERROR_MESSAGE);
    }
}
